<?php

require "../utility.php";

function deleteCodeFromDatabase(mysqli $conn, string $id) {
    $delete_str = "DELETE FROM Codes WHERE ID = ?;";
    $delete_stmt = $conn->prepare($delete_str);
    $delete_stmt->bind_param("s", $id);
    $delete_stmt->execute();
}

function verifyCode(mysqli $conn, string $id, string $code): bool {
    $query_str = "SELECT raw FROM Codes WHERE ID = '$id' AND raw = '$code';";
    $query = $conn->query($query_str);
    if ($query->fetch_row()) {
        deleteCodeFromDatabase($conn, $id);
        return true;
    }
    return false;
}

$json = getJsonDataFromRawInput();

http_response_code(403);

if (check_keys($json, "ID", "code")) {
    $id   = $json["ID"];
    $code = $json["code"];

    if (strlen($code) == 4) {
        $conn = connect_mysql();
        if (verifyCode($conn, $id, $code)) {
            http_response_code(200);
        }
        $conn->close();
    }
}

?>